<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="一天在面试中，面试官给了我一道手写代码题 123456&#x2F;**    * 实现函数 partialUsingArguments，调用之后满足如下条件：    1、返回一个函数 result    2、调用 result 之后，返回的结果与调用函数 fn 的结果一致    3、fn 的调用参数为 partialUsingArguments 的第一个参数之后的全部参数以及 result 的调用参数*&#x2F;">
<meta property="og:type" content="article">
<meta property="og:title" content="js函数式编程">
<meta property="og:url" content="https://hxy1997.xyz/2021/04/22/js%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="一天在面试中，面试官给了我一道手写代码题 123456&#x2F;**    * 实现函数 partialUsingArguments，调用之后满足如下条件：    1、返回一个函数 result    2、调用 result 之后，返回的结果与调用函数 fn 的结果一致    3、fn 的调用参数为 partialUsingArguments 的第一个参数之后的全部参数以及 result 的调用参数*&#x2F;">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421104447.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421104612.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421105339.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102848.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102902.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102939.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102934.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102959.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421103013.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421103028.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210605153710.png">
<meta property="article:published_time" content="2021-04-21T16:00:00.000Z">
<meta property="article:modified_time" content="2021-06-14T09:31:29.948Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="javascript">
<meta property="article:tag" content="函数式编程">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421104447.webp">

<link rel="canonical" href="https://hxy1997.xyz/2021/04/22/js%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>js函数式编程 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/04/22/js%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          js函数式编程
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-22 00:00:00" itemprop="dateCreated datePublished" datetime="2021-04-22T00:00:00+08:00">2021-04-22</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-06-14 17:31:29" itemprop="dateModified" datetime="2021-06-14T17:31:29+08:00">2021-06-14</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/04/22/js%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/04/22/js%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>一天在面试中，面试官给了我一道手写代码题</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment">    * 实现函数 partialUsingArguments，调用之后满足如下条件：</span></span><br><span class="line"><span class="comment">    1、返回一个函数 result</span></span><br><span class="line"><span class="comment">    2、调用 result 之后，返回的结果与调用函数 fn 的结果一致</span></span><br><span class="line"><span class="comment">    3、fn 的调用参数为 partialUsingArguments 的第一个参数之后的全部参数以及 result 的调用参数</span></span><br><span class="line"><span class="comment">*/</span> </span><br></pre></td></tr></table></figure>

<p>我当时的第一版思路，将两个参数数组进行拼接，通过闭包返回结果，面试官提示如果参数为空，怎么办，我增加了args = args || [];这一句</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">partialUsingArguments</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">    args = args || [];</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">..._args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn(args.concat(_args));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>面试官说如果参数不是数组，是对象怎么办，提示ES6还有什么拼接方法，使用展开运算符</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">partialUsingArguments</span>(<span class="params">fn, args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">_args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn(...args, ..._args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>我当场问面试官，是不是函数柯里化，其实这和柯里化一样，叫作偏函数，和函数柯里化一样，都属于函数式编程的范畴，这里总结了一些函数式编程的经典案例，吃透它们吧。</p>
<p>推荐阅读:</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://llh911001.gitbooks.io/mostly-adequate-guide-chinese/content/">《函数式编程指北》</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/Simingchen/Functional-Light-JS">《JavaScript轻量级函数式编程》</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/ruanyf/es6tutorial/blob/gh-pages/docs/fp.md">《ECMAScript 6入门》——函数式编程</a>或者<a target="_blank" rel="noopener" href="https://www.bookstack.cn/read/es6-3rd/docs-fp.md">电子书版</a></li>
</ul>
<span id="more"></span>

<h2 id="1-什么是函数式编程"><a href="#1-什么是函数式编程" class="headerlink" title="1.什么是函数式编程"></a>1.什么是函数式编程</h2><p>JavaScript 语言从一诞生，就具有函数式编程的烙印。它将函数作为一种独立的数据类型，与其他数据类型处于完全平等的地位。在 JavaScript 语言中，你可以采用面向对象编程，也可以采用函数式编程。有人甚至说，JavaScript 是有史以来第一种被大规模采用的函数式编程语言。 ES6 的种种新增功能，使得函数式编程变得更方便、更强大。</p>
<p>在文章之前，先和大家讲一下对于函数式编程（<em>Functional Programming, aka. FP</em>）的理解（下文使用FP指代函数式编程）：</p>
<ol>
<li>FP需要保证函数都是纯净的，既不依赖外部的状态变量，也不产生副作用。基于此前提下，那么纯函数的组合与调用，在时间顺序上就不会产生依赖，改变多个函数的调用顺序也不必担心产生问题，因此也会消灭许多潜在的bug。</li>
<li>函数必须有输入输出。如果一个函数缺乏输入或输出，那么它其实是一段处理程序<em>procedure</em>而已。</li>
<li>函数尽可能的保持功能的单一，如果一个函数做了多件事情，那么它理论上应当被拆分为多个函数。</li>
<li>FP的意义之一就是，在适当的时机使用声明式编程，抽象了程序流的控制与表现，从理解和维护的角度上会胜于命令式编程。</li>
<li>FP是一种范式，但并不意味这和OOP（面向对象编程）冲突，两者当然是可以和谐共存的。个人认为 <strong>React</strong> 其实就是一个很好的栗子~</li>
<li>Javascript的函数一等公民以及闭包的特性，决定了Javascript的确是适合施展FP的舞台</li>
</ol>
<h2 id="2-闭包"><a href="#2-闭包" class="headerlink" title="2.闭包"></a>2.闭包</h2><p>闭包对于 <strong>Javascript</strong> 来说，当然十分重要。然而对于函数式编程来说，这更加是必不可少的，必须掌握的概念，闭包的定义如下：</p>
<blockquote>
<p>Closure is when a function remembers and accesses variables from outside of its own scope, even when that function is executed in a different scope.</p>
</blockquote>
<p>相信大部分同学都对闭包有不错的理解，但是由于对FP的学习十分重要。接下来我还是会啰嗦的带大家过一遍。<strong>闭包就是能够读取其他函数内部变量的函数</strong></p>
<p>简单示例如下</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Closure demo</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cube</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">let</span> z = <span class="number">1</span>;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">larger</span>(<span class="params">y</span>) </span>&#123;</span><br><span class="line">    	<span class="keyword">return</span> x * y * z++;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> makeCube = cube(<span class="number">10</span>);</span><br><span class="line"><span class="built_in">console</span>.log(makeCube(<span class="number">5</span>)); <span class="comment">// 50</span></span><br><span class="line"><span class="built_in">console</span>.log(makeCube(<span class="number">5</span>)); <span class="comment">// 100</span></span><br></pre></td></tr></table></figure>

<p>那么有没有想过在函数makeCube，或者也可以说是函数larger是怎么记住原本不属于自己作用域的变量x和z的呢？在控制台查看<code>makeCube.prototype</code>，点开会发现原来是有个<code>[[Scopes]]</code>这个内置属性里的<code>Closure(cube)</code>记住了函数larger返回时记住的变量x和z。如果多嵌套几层函数，也会发现多几个Closure(name)在<code>[[Scopes]]</code>的<code>Scopes[]</code>数组里，按序查找变量。</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421104447.webp" alt="img"></p>
<p>再看下图测试代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cube</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">wrapper</span>(<span class="params">y</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> z = <span class="number">1</span>;</span><br><span class="line">        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">larger</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        	<span class="keyword">return</span> x * y * z++;</span><br><span class="line">        &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> makeCubeY = cube(<span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> makeCube = makeCubeY(<span class="number">5</span>);</span><br><span class="line"><span class="keyword">const</span> $__VAR1__ = <span class="string">&#x27;1. This var is just for test.&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> $__VAR2__ = <span class="string">&#x27;2. This var is just for test.&#x27;</span>;</span><br><span class="line"><span class="keyword">var</span> $__VAR3__ = <span class="string">&#x27;3. This var is just for test.&#x27;</span>;</span><br><span class="line"><span class="built_in">console</span>.log(makeCubeY.prototype, makeCube.prototype);</span><br><span class="line"><span class="built_in">console</span>.log(makeCube()); <span class="comment">// 50</span></span><br><span class="line"><span class="built_in">console</span>.log(makeCube()); <span class="comment">// 100</span></span><br></pre></td></tr></table></figure>

<p>打印<code>makeCubeY.prototype</code>：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421104612.webp" alt="img"></p>
<p>打印<code>makeCube.prototype</code>：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421105339.webp" alt="img"></p>
<p>通过这几个实验可以从另一个角度去理解Javascript中闭包，一个闭包是怎么去查找不是自己作用域的变量呢？makeCube函数分别从<code>[[Scopes]]</code>中的Closure(wrapper)里找到变量y、z，Closure(cube)里找到变量x。至于全局let、const声明的变量放在了<code>Script</code>里，全局var声明的变量放在了<code>Global</code>里。</p>
<p>在学习FP前，理解闭包是尤为重要的~ 因为事实上大量的FP工具函数都使用了闭包这个特性。</p>
<h2 id="3-unary"><a href="#3-unary" class="headerlink" title="3.unary"></a>3.unary</h2><h3 id="ES6简化写法"><a href="#ES6简化写法" class="headerlink" title="ES6简化写法"></a>ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> unary = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">arg</span> =&gt;</span> fn(arg);</span><br></pre></td></tr></table></figure>

<p>一元函数，应用于当只想在<strong>某个函数上传递一个参数</strong>情况下使用。尝试考虑以下场景：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log([<span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;3&#x27;</span>].map(<span class="built_in">parseInt</span>)); <span class="comment">// [1, NaN, NaN]</span></span><br><span class="line"><span class="built_in">console</span>.log([<span class="string">&#x27;1&#x27;</span>, <span class="string">&#x27;2&#x27;</span>, <span class="string">&#x27;3&#x27;</span>].map(unary(<span class="built_in">parseInt</span>))); <span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>

<p><code>parseInt(string, radix)</code>接收两个参数，而map函数中接收的回调函数<code>callback(currentValue[, index[, array]])</code>，第二个参数是index，此时如果parseInt的使用就是错误的，[‘1’, ‘2’, ‘3’].map(parseInt)会计算parseInt(1, 0), parseInt(2, 1)和parseInt(3, 2)的值。当然除了<code>Array.prototype.map</code>，大量内置的数组方法中的回调函数中都不止传递一个参数，如果存在适用的只需要第一个参数的场景，unary函数就发挥了它的价值，无需修改函数，优雅简洁地就接入了。对于unary函数，fn就是闭包记忆的变量数据，可以将函数展开为</p>
<h3 id="ES6常规写法"><a href="#ES6常规写法" class="headerlink" title="ES6常规写法"></a>ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> unary = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">arg</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn(arg);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="4-identity"><a href="#4-identity" class="headerlink" title="4.identity"></a>4.identity</h2><h3 id="ES6简化写法-1"><a href="#ES6简化写法-1" class="headerlink" title="ES6简化写法"></a>ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> identity = <span class="function"><span class="params">v</span> =&gt;</span> v;</span><br></pre></td></tr></table></figure>

<p>将函数展开为</p>
<h3 id="ES6常规写法-1"><a href="#ES6常规写法-1" class="headerlink" title="ES6常规写法"></a>ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> identity = <span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> v;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>有同学会看到identity函数会觉得莫名其妙？是干嘛的？我第一眼看到也很迷惑？但是考虑以下场景：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log([<span class="literal">false</span>, <span class="number">1</span>, <span class="number">2</span>, <span class="number">0</span>, <span class="string">&#x27;5&#x27;</span>, <span class="literal">true</span>].filter( identity )); <span class="comment">// [1, 2, &quot;5&quot;, true]</span></span><br><span class="line"><span class="built_in">console</span>.log([<span class="literal">false</span>, <span class="number">0</span>].some( identity )); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">console</span>.log([-<span class="number">2</span>, <span class="number">1</span>, <span class="string">&#x27;3&#x27;</span>].every( identity )); <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>怎么样？眼前一亮吧，没想到<code>identity</code>函数原来深藏不露，事实上虽然identity返回了原值，但是在这些函数中Javascript会对返回的值进行类型装换，变成了布尔值。比如filter函数。我们可以看MDN定义filter描述如下（看标粗的那一句）。</p>
<blockquote>
<p>filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for <strong>which callback returns a value that coerces to true.</strong></p>
</blockquote>
<h2 id="5-constant"><a href="#5-constant" class="headerlink" title="5.constant"></a>5.constant</h2><h3 id="ES6简化写法-2"><a href="#ES6简化写法-2" class="headerlink" title="ES6简化写法"></a>ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> constant = <span class="function"><span class="params">v</span> =&gt;</span> <span class="function">() =&gt;</span> v;</span><br></pre></td></tr></table></figure>

<p>将函数展开为</p>
<h3 id="ES6常规写法-2"><a href="#ES6常规写法-2" class="headerlink" title="ES6常规写法"></a>ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> constant = <span class="function"><span class="keyword">function</span>(<span class="params">v</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> v;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>同样，这个函数…乍一看，也不知道具体有什么用。但是考虑场景如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    	resolve(<span class="string">&#x27;Hello!&#x27;</span>);</span><br><span class="line">    &#125;, <span class="number">200</span>);</span><br><span class="line">&#125;);</span><br><span class="line">p1.then(constant(<span class="string">&#x27;Hi&#x27;</span>)).then(<span class="built_in">console</span>.log); <span class="comment">// Hi!</span></span><br></pre></td></tr></table></figure>

<p>引入constant函数简化函数</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    	resolve(<span class="string">&#x27;Hello!&#x27;</span>);</span><br><span class="line">    &#125;, <span class="number">200</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="keyword">const</span> constant = <span class="function"><span class="params">v</span> =&gt;</span> <span class="function">() =&gt;</span> v;</span><br><span class="line">p1.then(constant(<span class="string">&#x27;Hi&#x27;</span>)).then(<span class="built_in">console</span>.log); <span class="comment">// Hi!</span></span><br></pre></td></tr></table></figure>

<p>而直接传参数会出现Promise中的值穿透</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> p1 = <span class="keyword">new</span> <span class="built_in">Promise</span>(<span class="function">(<span class="params">resolve, reject</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    	resolve(<span class="string">&#x27;Hello!&#x27;</span>);</span><br><span class="line">    &#125;, <span class="number">200</span>);</span><br><span class="line">&#125;);</span><br><span class="line">p1.then(<span class="string">&#x27;Hi&#x27;</span>).then(<span class="built_in">console</span>.log); <span class="comment">// Hello!</span></span><br></pre></td></tr></table></figure>

<p>由于<code>Promise.prototype.then</code>只接受函数，如果我仅仅只需要传递一个值时，那么<code>constant</code>便会提供这种便利。当然这个并没有什么功能上的提升，但是的确提高了可阅读性，也是函数式编程的一个优点。</p>
<h2 id="6-spreadArgs-amp-gatherArgs"><a href="#6-spreadArgs-amp-gatherArgs" class="headerlink" title="6.spreadArgs &amp; gatherArgs"></a>6.spreadArgs &amp; gatherArgs</h2><h3 id="ES6简化写法-3"><a href="#ES6简化写法-3" class="headerlink" title="ES6简化写法"></a>ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> spreadArgs = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">argsArr</span> =&gt;</span> fn(...argsArr );</span><br><span class="line"><span class="keyword">const</span> gatherArgs = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function">(<span class="params">...argsArr</span>) =&gt;</span> fn(argsArr);</span><br></pre></td></tr></table></figure>

<p>将函数展开为</p>
<h3 id="ES6常规写法-3"><a href="#ES6常规写法-3" class="headerlink" title="ES6常规写法"></a>ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> spreadArgs = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">argsArr</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn(...argsArr);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> gatherArgs = <span class="function"><span class="keyword">function</span>(<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...argsArr</span>) </span>&#123;</span><br><span class="line">		<span class="keyword">return</span> fn(argsArr);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>嗯这两个函数见名知义。<code>spreadArgs</code>函数用于展开一个函数的所有参数，<code>gatherArgs</code>函数收集一个函数的所有参数，这两个函数明显对立，那么它们的应用场景又是什么呢？</p>
<p>spreadArgs函数示例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cube</span>(<span class="params">x, y, z</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y * z;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">make</span>(<span class="params">fn, points</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> fn(points);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> spreadArgs = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function"><span class="params">argsArr</span> =&gt;</span> fn(...argsArr );</span><br><span class="line"><span class="built_in">console</span>.log(make(cube, [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])); <span class="comment">// NaN</span></span><br><span class="line"><span class="built_in">console</span>.log(make(spreadArgs(cube), [<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>])); <span class="comment">// 60</span></span><br></pre></td></tr></table></figure>

<p>gatherArgs函数示例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">combineFirstTwo</span>(<span class="params">[v1, v2]</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> v1 + v2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> gatherArgs = <span class="function"><span class="params">fn</span> =&gt;</span> <span class="function">(<span class="params">...argsArr</span>) =&gt;</span> fn(argsArr);</span><br><span class="line"><span class="comment">// console.log([1, 2, 3, 4, 5].reduce(combineFirstTwo)); // Uncaught TypeError</span></span><br><span class="line"><span class="built_in">console</span>.log([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>].reduce(gatherArgs(combineFirstTwo))); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<p>看完以上代码，简单的两个工具函数，轻易的做到了对一个函数的转换，从而使其适用于另一个场景。如果从此应该可以瞥见函数式编程的一点点魅力，那么下面的两个函数将给大家带来更多的惊喜。</p>
<h2 id="7-partial-amp-curry（偏函数与柯里化）"><a href="#7-partial-amp-curry（偏函数与柯里化）" class="headerlink" title="7.partial &amp; curry（偏函数与柯里化）"></a>7.partial &amp; curry（偏函数与柯里化）</h2><p>相信大家对函数柯里化应该或多或少有点了解。维基百科定义：</p>
<blockquote>
<p>在计算机科学中，柯里化（英语：Currying），又译为卡瑞化或加里化，是把接受多个参数的函数变换成接受一个单一参数（最初函数的第一个参数）的函数，并且返回接受余下的参数而且返回结果的新函数的技术。</p>
</blockquote>
<p>当然得益于闭包的强大威力，柯里化这个武器得以诞生于Javascript世界。</p>
<p>我面试的那个问题本质上就是partial偏函数，和柯里化有点类似，所以没见过的我当场做完之后问了一下是不是函数的柯里化，想想也知道不是，知识两者类似</p>
<h3 id="偏函数ES6简化写法"><a href="#偏函数ES6简化写法" class="headerlink" title="偏函数ES6简化写法"></a>偏函数ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br></pre></td></tr></table></figure>

<p>把我的手写版本改成相同的格式，作为其展开版本，</p>
<h3 id="偏函数ES6常规写法"><a href="#偏函数ES6常规写法" class="headerlink" title="偏函数ES6常规写法"></a>偏函数ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">partial</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">..._args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn(...args, ..._args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>函数柯里化也同样利用用闭包把参数保存起来，当参数的数量足够执行函数了，就开始执行函数。</p>
<h3 id="函数柯里化ES6常规写法"><a href="#函数柯里化ES6常规写法" class="headerlink" title="函数柯里化ES6常规写法"></a>函数柯里化ES6常规写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">const</span> len = fn.length;</span><br><span class="line">	<span class="keyword">if</span> (args.length &gt;= len) &#123;</span><br><span class="line">    	<span class="comment">// 判断当前函数传入的参数是否大于或等于fn需要参数的数量，如果是，直接执行fn</span></span><br><span class="line">    	<span class="keyword">return</span> fn(...args);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">..._args</span>) </span>&#123;</span><br><span class="line">    	<span class="comment">// 如果传入参数数量不够，返回一个闭包，暂存传入的参数，并重新返回curry函数</span></span><br><span class="line">		<span class="keyword">return</span> curry.call(<span class="built_in">this</span>, fn, ...args, ..._args);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiFn</span>(<span class="params">a, b, c</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a * b * c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> multi = curry(multiFn);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">2</span>)(<span class="number">3</span>)(<span class="number">4</span>)); <span class="comment">// 24</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)); <span class="comment">// 60</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">4</span>)(<span class="number">5</span>, <span class="number">6</span>)); <span class="comment">// 120</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">5</span>, <span class="number">6</span>)(<span class="number">7</span>)); <span class="comment">// 210</span></span><br></pre></td></tr></table></figure>

<p>经过一些简化的方法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (args.length &gt;= fn.length) &#123;</span><br><span class="line">    	<span class="comment">// 判断当前函数传入的参数是否大于或等于fn需要参数的数量，如果是，直接执行fn</span></span><br><span class="line">    	<span class="keyword">return</span> fn(...args);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="comment">// 如果传入参数数量不够，返回一个闭包，暂存传入的参数，并重新返回curry函数</span></span><br><span class="line">    	<span class="keyword">return</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span> curry(fn, ...args, ..._args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiFn</span>(<span class="params">a, b, c</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a * b * c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> multi = curry(multiFn);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">2</span>)(<span class="number">3</span>)(<span class="number">4</span>)); <span class="comment">// 24</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)); <span class="comment">// 60</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">4</span>)(<span class="number">5</span>, <span class="number">6</span>)); <span class="comment">// 120</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">5</span>, <span class="number">6</span>)(<span class="number">7</span>)); <span class="comment">// 210</span></span><br></pre></td></tr></table></figure>

<h3 id="函数柯里化ES6简化写法"><a href="#函数柯里化ES6简化写法" class="headerlink" title="函数柯里化ES6简化写法"></a>函数柯里化ES6简化写法</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> curry = <span class="function">(<span class="params">fn, arr = []</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span> (</span><br><span class="line">	args =&gt; args.length === fn.length ? fn(...args) : curry(fn, args)</span><br><span class="line">)([...arr, ..._args])</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiFn</span>(<span class="params">a, b, c</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> a * b * c;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> multi = curry(multiFn);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">2</span>)(<span class="number">3</span>)(<span class="number">4</span>)); <span class="comment">// 24</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>)); <span class="comment">// 60</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">4</span>)(<span class="number">5</span>, <span class="number">6</span>)); <span class="comment">// 120</span></span><br><span class="line"><span class="built_in">console</span>.log(multi(<span class="number">5</span>, <span class="number">6</span>)(<span class="number">7</span>)); <span class="comment">// 210</span></span><br></pre></td></tr></table></figure>

<p>请大家先精读以上关于partial、curry函数的代码。</p>
<p>先模拟一个ajax函数如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url, params, callback</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        callback(</span><br><span class="line">        	<span class="string">`GET <span class="subst">$&#123;url&#125;</span> \nparams: <span class="subst">$&#123;params&#125;</span> \ndata: Hello! <span class="subst">$&#123;params&#125;</span> `</span></span><br><span class="line">        );</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>考虑partial使用场景如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url, params, callback</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        callback(</span><br><span class="line">        	<span class="string">`GET <span class="subst">$&#123;url&#125;</span> \nparams: <span class="subst">$&#123;params&#125;</span> \ndata: Hello! <span class="subst">$&#123;params&#125;</span> `</span></span><br><span class="line">        );</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">partial</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> (<span class="params">..._args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> fn(...args, ..._args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fetchPerson = partial( ajax, <span class="string">&quot;http://some.api/person&quot;</span> );</span><br><span class="line"></span><br><span class="line">fetchPerson(<span class="string">&#x27;Teddy Bear&#x27;</span>, <span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">GET http://some.api/person </span></span><br><span class="line"><span class="comment">params: Teddy Bear </span></span><br><span class="line"><span class="comment">data: Hello! Teddy Bear </span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>考虑curry使用场景如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">ajax</span>(<span class="params">url, params, callback</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">setTimeout</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">        callback(</span><br><span class="line">        	<span class="string">`GET <span class="subst">$&#123;url&#125;</span> \nparams: <span class="subst">$&#123;params&#125;</span> \ndata: Hello! <span class="subst">$&#123;params&#125;</span> `</span></span><br><span class="line">        );</span><br><span class="line">    &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">curry</span>(<span class="params">fn, ...args</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">if</span> (args.length &gt;= fn.length) &#123;</span><br><span class="line">    	<span class="comment">// 判断当前函数传入的参数是否大于或等于fn需要参数的数量，如果是，直接执行fn</span></span><br><span class="line">    	<span class="keyword">return</span> fn(...args);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="comment">// 如果传入参数数量不够，返回一个闭包，暂存传入的参数，并重新返回curry函数</span></span><br><span class="line">    	<span class="keyword">return</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span> curry(fn, ...args, ..._args);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fetchPerson = curry(ajax)(<span class="string">&#x27;http://some.api/person&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> fetchUncleBarney = fetchPerson(<span class="string">&#x27;Uncle Barney&#x27;</span>);</span><br><span class="line"></span><br><span class="line">fetchUncleBarney(<span class="built_in">console</span>.log);</span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">GET http://some.api/person </span></span><br><span class="line"><span class="comment">params: Uncle Barney </span></span><br><span class="line"><span class="comment">data: Hello! Uncle Barney </span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<p>partial和curry函数功能相似，但又有具体的不同应用场景，但总体来说curry会比partial更自动化一点。</p>
<p>但是！相信看完示例的同学又会有一连串问号？为什么好好地参数不一次性传入，而非要分开多次传入这么麻烦？原因如下：</p>
<ol>
<li>最首要的原因是partial和curry函数都允许我们通过参数控制将一个函数的调用在时间和空间上分开了。传统函数需要一次性将参数凑齐才能调用，但是有时候我们可以提前预置部分参数，在最终需要触发此函数时，才将剩余参数传入。这时候partial和curry就会变得十分有用。</li>
<li>partial和curry的存在让函数组合（<em>compose</em>）会更加便利。</li>
<li>当然最重要是也提升了可阅读性！一开始可能不这么以为，但是如果你实践操作感受之后，也许会改观。</li>
</ol>
<p>P.S. 关于函数式编程的实践，大家可以使用<code>lodash/fp</code>模块进行入门实践。</p>
<h2 id="8-compose（函数合成）"><a href="#8-compose（函数合成）" class="headerlink" title="8.compose（函数合成）"></a>8.compose（函数合成）</h2><p>函数合成（function composition）指的是，将多个函数合成一个函数。</p>
<p>如果我们想，对一个值执行一系列操作，并打印出来，考虑以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(add10(pow3(double(<span class="number">2</span>)))); <span class="comment">// 74</span></span><br></pre></td></tr></table></figure>

<p>上面代码中，<code>compose</code>就是一个函数合成器，用于将两个函数合成一个函数。</p>
<p>备注：<code>partialRight</code>和<code>partial</code>见名知意，相当于是彼此的镜像函数。</p>
<blockquote>
<p>_.partialRight: This method is like _.partial except that partially applied arguments are appended to the arguments it receives.</p>
</blockquote>
<p>原文从lodash导入，我自己仿照partial重写了一版。无需否认，这段示例代码的确毫无意义。但是为了达成这一系列操作，我最终执行了这一长串嵌套了四层的函数调用：<code>console.log(add10(pow3(double(2))))</code>。（说实话，我的确觉得有点难以阅读了…），如果更长了，怎么办？可能有的同学会给出以下答案:</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">mixed</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> add10(pow3(double(<span class="number">2</span>)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(mixed(<span class="number">2</span>)); <span class="comment">// 74</span></span><br></pre></td></tr></table></figure>

<p>的确，看似好了点，但是也只是将这个冗长的调用封装了一下而已。会不会有更好的做法？</p>
<h3 id="基于栈的compose函数"><a href="#基于栈的compose函数" class="headerlink" title="基于栈的compose函数"></a>基于栈的compose函数</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">result</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">const</span> funcs = [...args];</span><br><span class="line">        <span class="keyword">while</span>(funcs.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">            result = funcs.pop()(result);</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line">compose(<span class="built_in">console</span>.log, add10, pow3, double)(<span class="number">2</span>) <span class="comment">// 74</span></span><br></pre></td></tr></table></figure>

<p>欧耶！我们通过实现了一个简单的<code>compose</code>函数，然后发现调用的过程<code>compose(console.log, add10, pow3, double)(2)</code>竟然变得如此优雅！多个函数的调用从代码阅读上，多层嵌套被拍平变成了线性！（当然实际上本质上还是嵌套的函数调用的）。</p>
<h3 id="使用函数reduce的compose函数"><a href="#使用函数reduce的compose函数" class="headerlink" title="使用函数reduce的compose函数"></a>使用函数reduce的compose函数</h3><p>当然，关于<code>compose</code>的更加函数式的实现如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">result</span> =&gt;</span> funcs</span><br><span class="line">        .reverse()</span><br><span class="line">        .reduce(<span class="function">(<span class="params">result, fn</span>) =&gt;</span> fn(result), result);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line">compose(<span class="built_in">console</span>.log, add10, pow3, double)(<span class="number">2</span>) <span class="comment">// 74</span></span><br></pre></td></tr></table></figure>

<p>那么有同学可能也发现了，上述<code>compose</code>之后的函数是只可以传递一个参数的。这无疑显得有点蠢？难道不可以优化实现支持多个参数么？</p>
<p>考虑以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* function compose(...funcs) &#123;</span></span><br><span class="line"><span class="comment">    return funcs</span></span><br><span class="line"><span class="comment">        .reverse()</span></span><br><span class="line"><span class="comment">        .reduce((fn1, fn2) =&gt; (...args) =&gt; fn2(fn1(...args)));</span></span><br><span class="line"><span class="comment">&#125; */</span></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line">        .reduce(<span class="function">(<span class="params">fn1, fn2</span>) =&gt;</span> <span class="function">(<span class="params">...args</span>) =&gt;</span> fn1(fn2(...args)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line">compose(<span class="built_in">console</span>.log, add10, pow3, double)(<span class="number">2</span>) <span class="comment">// 74</span></span><br></pre></td></tr></table></figure>

<p>细心观察，通过将参数传递进行懒执行，从而巧妙的完成了这个任务！示例如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line">        .reduce(<span class="function">(<span class="params">fn1, fn2</span>) =&gt;</span> <span class="function">(<span class="params">...args</span>) =&gt;</span> fn1(fn2(...args)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">compose(</span><br><span class="line">	<span class="built_in">console</span>.log, add10, pow3, multiply</span><br><span class="line">)(<span class="number">2</span>, <span class="number">5</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<p>当然上述代码最终也可以这么写：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line">        .reduce(<span class="function">(<span class="params">fn1, fn2</span>) =&gt;</span> <span class="function">(<span class="params">...args</span>) =&gt;</span> fn1(fn2(...args)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">compose(</span><br><span class="line">    <span class="built_in">console</span>.log, </span><br><span class="line">    partial(add, <span class="number">10</span>),</span><br><span class="line">    partialRight(pow, <span class="number">3</span>),</span><br><span class="line">    partial(multiply, <span class="number">5</span>)</span><br><span class="line">)(<span class="number">2</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<h3 id="使用递归来实现compose"><a href="#使用递归来实现compose" class="headerlink" title="使用递归来实现compose"></a>使用递归来实现compose</h3><p>递归版本的<code>compose</code>本质上更接近概念，但是可能也会让人难以理解。了解一下也不错~</p>
<p>代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">compose</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> [fn1, fn2, ...rest] = funcs.reverse();</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">composed</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    	<span class="keyword">return</span> fn2(fn1(...args));</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (rest.length === <span class="number">0</span>) <span class="keyword">return</span> composed;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> compose(</span><br><span class="line">        ...rest.reverse(),</span><br><span class="line">        composed</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> add10 = partial(add, <span class="number">10</span>);</span><br><span class="line"><span class="keyword">const</span> pow3 = partialRight(pow, <span class="number">3</span>);</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">compose(</span><br><span class="line">	<span class="built_in">console</span>.log, add10, pow3, multiply</span><br><span class="line">)(<span class="number">2</span>, <span class="number">5</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<h3 id="redux-amp-koa-compose"><a href="#redux-amp-koa-compose" class="headerlink" title="redux &amp; koa-compose"></a>redux &amp; koa-compose</h3><p>redux以及koa其实都是有中间件的思想，组合中间件的compose原理和上述代码也相差不远。大家可以稍微阅读以下两个链接的源码，代码都很简短，但都验证了compose的概念只要在实际开发中运用得当的话，可以发挥强大的魔力！</p>
<ul>
<li><a target="_blank" rel="noopener" href="https://github.com/reduxjs/redux/blob/master/src/compose.js">redux/src/compose.js</a></li>
<li><a target="_blank" rel="noopener" href="https://github.com/koajs/compose/blob/master/index.js">koa-compose</a></li>
</ul>
<h2 id="9-pipe（管道-序列）"><a href="#9-pipe（管道-序列）" class="headerlink" title="9.pipe（管道/序列）"></a>9.pipe（管道/序列）</h2><p>那么学习完了<code>compose</code>，<code>pipe</code>又是什么呢？首先在刚刚学习<code>compose</code>函数时，可能有同学会觉得有点小别扭，因为<code>compose</code>从左到右传递参数的顺序刚好和调用顺序相反的！</p>
<p>（当然如果说帮助理解记忆的话，compose传参的顺序就是我们书写函数嵌套的顺序，在脑海里把<code>console.log(add10(pow3(double(2))))</code>这一长串里的括号去了，是不是就是参数的顺序了~）</p>
<p>回到话题，<code>pipe</code>是什么？同学们有没有使用过命令行，比如我常用的一个命令，将当前工作路径拷贝到剪切板，随时ctrl + v就可以使用了~</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">pwd</span> | pbcopy</span><br></pre></td></tr></table></figure>

<p>当然我木有走题！注意以上的管道符 <code>|</code>，这个其实就是<code>pipe</code>，可以将数据流从左到右传递。</p>
<h3 id="基于队列的pipe函数"><a href="#基于队列的pipe函数" class="headerlink" title="基于队列的pipe函数"></a>基于队列的pipe函数</h3><p>考虑的pipe示例代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pipe</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">result</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">const</span> funcs = [...args];</span><br><span class="line">    <span class="keyword">while</span>(funcs.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">    	result = funcs.shift()(result);</span><br><span class="line">    &#125;</span><br><span class="line">    	<span class="keyword">return</span> result;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">pipe(</span><br><span class="line">    partial(multiply, <span class="number">5</span>),</span><br><span class="line">    partialRight(pow, <span class="number">3</span>),</span><br><span class="line">    partial(add, <span class="number">10</span>),</span><br><span class="line">    <span class="built_in">console</span>.log</span><br><span class="line">)(<span class="number">2</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<p>等等，从左到右？好像和compose刚好相反诶！而且这段代码好眼熟啊！将pop方法换成了shift方法而已！</p>
<p>那么实际上等价于：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> reverseArgs = <span class="function"><span class="params">func</span> =&gt;</span> <span class="function">(<span class="params">...args</span>) =&gt;</span> func(...args.reverse());</span><br><span class="line"><span class="keyword">const</span> pipe = reverseArgs(compose);</span><br></pre></td></tr></table></figure>

<p>哈我们避免了重复无意义的代码！当然无论是<code>compose</code>还是<code>pipe</code>，本质上我们都将命令式的代码转换成了声明式的代码，对一个值的操作可以理解为值在函数之间流动</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">2</span> --&gt; multiply --&gt; pow --&gt; add --&gt; <span class="built_in">console</span>.log</span><br></pre></td></tr></table></figure>

<p>多么优雅呀~</p>
<h3 id="使用函数reduce的pipe函数"><a href="#使用函数reduce的pipe函数" class="headerlink" title="使用函数reduce的pipe函数"></a>使用函数reduce的pipe函数</h3><p>也可以实现关于<code>pipe</code>的更加函数式的实现如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pipe</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="params">result</span> =&gt;</span> funcs</span><br><span class="line">        .reduce(<span class="function">(<span class="params">result, fn</span>) =&gt;</span> fn(result), result);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">pipe(</span><br><span class="line">    partial(multiply, <span class="number">5</span>),</span><br><span class="line">    partialRight(pow, <span class="number">3</span>),</span><br><span class="line">    partial(add, <span class="number">10</span>),</span><br><span class="line">    <span class="built_in">console</span>.log</span><br><span class="line">)(<span class="number">2</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<p>上述<code>pipe</code>之后的函数是只可以传递一个参数的。优化实现支持多个参数么</p>
<p>考虑以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pipe</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> funcs</span><br><span class="line">        .reduce(<span class="function">(<span class="params">fn1, fn2</span>) =&gt;</span> <span class="function">(<span class="params">...args</span>) =&gt;</span> fn2(fn1(...args)));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">pipe(</span><br><span class="line">    partial(multiply, <span class="number">5</span>),</span><br><span class="line">    partialRight(pow, <span class="number">3</span>),</span><br><span class="line">    partial(add, <span class="number">10</span>),</span><br><span class="line">    <span class="built_in">console</span>.log</span><br><span class="line">)(<span class="number">2</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>

<h3 id="使用递归来实现pipe"><a href="#使用递归来实现pipe" class="headerlink" title="使用递归来实现pipe"></a>使用递归来实现pipe</h3><p>递归版本的<code>pipe</code>本质上更接近概念，但是可能也会让人难以理解。</p>
<p>代码如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pipe</span>(<span class="params">...funcs</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> [fn1, fn2, ...rest] = funcs;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">piped</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">    	<span class="keyword">return</span> fn2(fn1(...args));</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">if</span> (rest.length === <span class="number">0</span>) <span class="keyword">return</span> piped;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> pipe(</span><br><span class="line">        ...rest,</span><br><span class="line">        piped</span><br><span class="line">    );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// import &#123; partial, partialRight &#125; from &#x27;lodash&#x27;;</span></span><br><span class="line"><span class="keyword">const</span> partial = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(...args, ..._args);</span><br><span class="line">	</span><br><span class="line"><span class="keyword">const</span> partialRight = <span class="function">(<span class="params">fn, ...args</span>) =&gt;</span> <span class="function">(<span class="params">..._args</span>) =&gt;</span></span><br><span class="line">	fn(..._args, ...args);</span><br><span class="line">	</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">pow</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> <span class="built_in">Math</span>.pow(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">double</span>(<span class="params">x</span>) </span>&#123;</span><br><span class="line">  	<span class="keyword">return</span> x * <span class="number">2</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">multiply</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> x * y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">pipe(</span><br><span class="line">    partial(multiply, <span class="number">5</span>),</span><br><span class="line">    partialRight(pow, <span class="number">3</span>),</span><br><span class="line">    partial(add, <span class="number">10</span>),</span><br><span class="line">    <span class="built_in">console</span>.log</span><br><span class="line">)(<span class="number">2</span>); <span class="comment">// 1010</span></span><br></pre></td></tr></table></figure>



<h2 id="10-Functor（函子）"><a href="#10-Functor（函子）" class="headerlink" title="10.Functor（函子）"></a>10.Functor（函子）</h2><h3 id="前言-什么是函子？"><a href="#前言-什么是函子？" class="headerlink" title="前言 什么是函子？"></a>前言 什么是函子？</h3><p><strong>定义</strong>：函子是一个普通对象（在其它语言中，可能是一个类），它实现了map函数，在遍历每个对象值的时候生成一个新对象。</p>
<h3 id="10-1-实现一个函子"><a href="#10-1-实现一个函子" class="headerlink" title="10.1 实现一个函子"></a>10.1 实现一个函子</h3><p>简言之，函子是一个持有值的容器。而且函子是一个普通对象。我们就可以创建一个容器（也就是对象），让它能够持有任何传给它的值。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Container = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> testValue = <span class="keyword">new</span> Container(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value:1&#125;</span></span><br></pre></td></tr></table></figure>

<p>我们给 Container 增加一个静态方法，它可以为我们在创建新的 Containers 时省略 new 关键字。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">Container.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> Container(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 现在我们就可以这样来创建</span></span><br><span class="line">Container.of(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value:1&#125;</span></span><br></pre></td></tr></table></figure>

<p>函子需要实现 map 方法，具体的实现是，map 函数从 Container 中取出值，传入的函数把取出的值作为参数调用，并将结果放回 Container。</p>
<blockquote>
<p>为什么需要 map 函数，我们上面实现的 Container 仅仅是持有了传给它的值。但是持有值的行为几乎没有任何应用场景，而 map 函数发挥的作用就是，允许我们使用当前 Container 持有的值调用任何函数。</p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">Container.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> Container.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 然后我们实现一个数字的 double 操作</span></span><br><span class="line"><span class="keyword">let</span> double = <span class="function">(<span class="params">x</span>) =&gt;</span> x + x;</span><br><span class="line">Container.of(<span class="number">3</span>).map(double);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value: 6&#125;</span></span><br></pre></td></tr></table></figure>

<p>map返回了一传入函数的执行结果为值的 Container 实例，所以我们可以链式操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Container.of(<span class="number">3</span>).map(double).map(double).map(double);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value: 24&#125;</span></span><br></pre></td></tr></table></figure>

<p>完整版代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Container = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Container.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> Container(value);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">Container.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> Container.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试</span></span><br><span class="line"><span class="comment">// 然后我们实现一个数字的 double 操作</span></span><br><span class="line"><span class="keyword">let</span> double = <span class="function">(<span class="params">x</span>) =&gt;</span> x + x;</span><br><span class="line">Container.of(<span class="number">3</span>).map(double).map(double).map(double);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value: 24&#125;</span></span><br></pre></td></tr></table></figure>

<p>使用ES6写法</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">of</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Container(value);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="title">map</span>(<span class="params">fn</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Container.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试</span></span><br><span class="line"><span class="comment">// 然后我们实现一个数字的 double 操作</span></span><br><span class="line"><span class="keyword">let</span> double = <span class="function">(<span class="params">x</span>) =&gt;</span> x + x;</span><br><span class="line">Container.of(<span class="number">3</span>).map(double).map(double).map(double);</span><br><span class="line"><span class="comment">// =&gt; Container &#123;value: 24&#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>通过以上的实现，我们可以发现，函子就是一个实现了map契约的对象。函子是一个寻求契约的概念，该契约很简单，就是实现 map 。根据实现 map 函数的方式不同，会产生不同类型的函子，如 MayBe 、 Either</strong></p>
<p>函子可以用来做什么？之前我们用tap函数来函数式的解决代码报错的调试问题，如何更加函数式的处理代码中的问题，那就需要用到下面我们说的MayBe函子</p>
<h3 id="10-2-MayBe-函子"><a href="#10-2-MayBe-函子" class="headerlink" title="10.2 MayBe 函子"></a>10.2 MayBe 函子</h3><p>让我们先写一个upperCase函数来假设一种场景</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> value = <span class="string">&#x27;string&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">upperCase</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 为了避免报错，我们得写这么一个判断</span></span><br><span class="line">    <span class="keyword">if</span>(value != <span class="literal">null</span> || value != <span class="literal">undefined</span>)</span><br><span class="line">        <span class="keyword">return</span> value.toUpperCase();</span><br><span class="line">&#125;</span><br><span class="line">upperCase(value);</span><br><span class="line"><span class="comment">// =&gt; STRING</span></span><br></pre></td></tr></table></figure>

<p>如上面所示，我们代码中经常需要判断一些<code>null</code>和<code>undefined</code>的情况。下面我们来看一下MayBe函子的实现。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MayBe 跟上面的 Container 很相似</span></span><br><span class="line"><span class="keyword">const</span> MayBe = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line">MayBe.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MayBe(value);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 多了一个isNothing</span></span><br><span class="line">MayBe.prototype.isNoting = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.value === <span class="literal">null</span> || <span class="built_in">this</span>.value === <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 函子必定有 map,但是 map 的实现方式可能不同</span></span><br><span class="line">MayBe.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : MayBe.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// MayBe应用</span></span><br><span class="line"><span class="keyword">let</span> value = <span class="string">&#x27;string&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">upperCase</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 函数无需么一个判断</span></span><br><span class="line">    <span class="keyword">return</span> value.toUpperCase();</span><br><span class="line">&#125;</span><br><span class="line">MayBe.of(value).map(upperCase);</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: &#x27;STRING&#x27; &#125;</span></span><br><span class="line"><span class="keyword">let</span> nullValue = <span class="literal">null</span>;</span><br><span class="line">MayBe.of(nullValue).map(upperCase);</span><br><span class="line"><span class="comment">// 不会报错 MayBe &#123; value: null &#125;</span></span><br></pre></td></tr></table></figure>

<p>写成ES6形式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MayBe 跟上面的 Container 很相似</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">MayBe</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">of</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> MayBe(value);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 多了一个isNothing</span></span><br><span class="line">    <span class="function"><span class="title">isNoting</span>(<span class="params"></span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.value === <span class="literal">null</span> || <span class="built_in">this</span>.value === <span class="literal">undefined</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="comment">// 函子必定有 map,但是 map 的实现方式可能不同</span></span><br><span class="line">    <span class="function"><span class="title">map</span>(<span class="params">fn</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : MayBe.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// MayBe应用</span></span><br><span class="line"><span class="keyword">let</span> value = <span class="string">&#x27;string&#x27;</span>;</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">upperCase</span>(<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 函数无需么一个判断</span></span><br><span class="line">    <span class="keyword">return</span> value.toUpperCase();</span><br><span class="line">&#125;</span><br><span class="line">MayBe.of(value).map(upperCase);</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: &#x27;STRING&#x27; &#125;</span></span><br><span class="line"><span class="keyword">let</span> nullValue = <span class="literal">null</span>;</span><br><span class="line">MayBe.of(nullValue).map(upperCase);</span><br><span class="line"><span class="comment">// 不会报错 MayBe &#123; value: null &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="10-3-Either-函子"><a href="#10-3-Either-函子" class="headerlink" title="10.3 Either 函子"></a>10.3 Either 函子</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">MayBe.of(<span class="string">&quot;tony&quot;</span>)</span><br><span class="line">    .map(<span class="function">() =&gt;</span> <span class="literal">undefined</span>)</span><br><span class="line">    .map((x)f =&gt; <span class="string">&quot;Mr. &quot;</span> + x);</span><br></pre></td></tr></table></figure>

<p>上面的代码结果是 <code>MyaBe &#123;value: null&#125;</code>,这只是一个简单的例子，我们可以想一下，如果代码比较复杂，我们是不知道到底是哪一个分支在检查 undefined 和 null 值时执行失败了。这时候我们就需要 Either 函子了，它能解决分支拓展问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> Nothing = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line">Nothing.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> Nothing(value);</span><br><span class="line">&#125;</span><br><span class="line">Nothing.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Some = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line">Some.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="keyword">new</span> Some(value);</span><br><span class="line">&#125;</span><br><span class="line">Some.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> Some.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Either = &#123;</span><br><span class="line">    Some,</span><br><span class="line">    Nothing</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 那么这里如何处理异常呢？</span></span><br><span class="line"><span class="comment">// 我们定义一个字符串转换成对象的函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseJSON</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 对于可能出错的环节使用try-catch</span></span><br><span class="line">    <span class="comment">// 正常情况使用Some函子</span></span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">        <span class="keyword">return</span> Either.Some.of(<span class="built_in">JSON</span>.parse(str));</span><br><span class="line">    &#125;<span class="keyword">catch</span> (e) &#123;</span><br><span class="line">        <span class="comment">// 错误之后使用Nothing函子，并返回错误信息</span></span><br><span class="line">        <span class="keyword">return</span> Either.Nothing.of(&#123; <span class="attr">error</span>: e.message &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> eS = parseJSON(<span class="string">&#x27;&#123;name:xm&#125;&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(eS);</span><br><span class="line"><span class="comment">// Nothing &#123; value: &#123; error: &#x27;Unexpected token n in JSON at position 1&#x27; &#125; &#125;</span></span><br><span class="line"><span class="keyword">let</span> eN = parseJSON(<span class="string">&#x27;&#123;&quot;name&quot;:&quot;xm&quot;&#125;&#x27;</span>)</span><br><span class="line"><span class="built_in">console</span>.log(eN);</span><br><span class="line"><span class="comment">// Some &#123; value: &#123; name: &#x27;xm&#x27; &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(eN.map(<span class="function"><span class="params">x</span> =&gt;</span> x.name.toUpperCase()));</span><br><span class="line"><span class="comment">// Some &#123; value: &#x27;XM&#x27; &#125;</span></span><br></pre></td></tr></table></figure>

<p>ES6代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Nothing</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">of</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Nothing(value);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">map</span>(<span class="params">fn</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">this</span>;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Some</span> </span>&#123;</span><br><span class="line">    <span class="function"><span class="title">constructor</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="built_in">this</span>.value = value;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">static</span> <span class="function"><span class="title">of</span>(<span class="params">value</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Some(value);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="function"><span class="title">map</span>(<span class="params">fn</span>)</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Some.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> Either = &#123;</span><br><span class="line">    Some,</span><br><span class="line">    Nothing</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 那么这里如何处理异常呢？</span></span><br><span class="line"><span class="comment">// 我们定义一个字符串转换成对象的函数</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">parseJSON</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// 对于可能出错的环节使用try-catch</span></span><br><span class="line">    <span class="comment">// 正常情况使用Some函子</span></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="keyword">return</span> Either.Some.of(<span class="built_in">JSON</span>.parse(str));</span><br><span class="line">    &#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">        <span class="comment">// 错误之后使用Nothing函子，并返回错误信息</span></span><br><span class="line">        <span class="keyword">return</span> Either.Nothing.of(&#123; <span class="attr">error</span>: e.message &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> eS = parseJSON(<span class="string">&#x27;&#123;name:xm&#125;&#x27;</span>);</span><br><span class="line"><span class="built_in">console</span>.log(eS);</span><br><span class="line"><span class="comment">// Nothing &#123; value: &#123; error: &#x27;Unexpected token n in JSON at position 1&#x27; &#125; &#125;</span></span><br><span class="line"><span class="keyword">let</span> eN = parseJSON(<span class="string">&#x27;&#123;&quot;name&quot;:&quot;xm&quot;&#125;&#x27;</span>)</span><br><span class="line"><span class="built_in">console</span>.log(eN);</span><br><span class="line"><span class="comment">// Some &#123; value: &#123; name: &#x27;xm&#x27; &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(eN.map(<span class="function"><span class="params">x</span> =&gt;</span> x.name.toUpperCase()));</span><br><span class="line"><span class="comment">// Some &#123; value: &#x27;XM&#x27; &#125;</span></span><br></pre></td></tr></table></figure>

<h3 id="10-4-Pointed-函子"><a href="#10-4-Pointed-函子" class="headerlink" title="10.4 Pointed 函子"></a>10.4 Pointed 函子</h3><p>函子只是一个实现了 map 契约的接口。Pointed 函子也是一个函子的子集，它具有实现了 of 契约的接口。 我们在 MayBe 和 Either 中也实现了 of 方法，用来在创建 Container 时不使用 new 关键字。所以 MayBe 和 Either 都可称为 Pointed 函子。</p>
<ul>
<li>Pointed 函子是实现了 of 静态方法的函子</li>
</ul>
<p>of 方法是为了避免使用 new 来创建对象，更深层的含义是<strong>of 方法用来把值放到上下文</strong></p>
<ul>
<li>Context（把值放到容器中，使用 map 来处理值）</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Container</span> </span>&#123; </span><br><span class="line">    <span class="comment">// Point函子</span></span><br><span class="line">    <span class="comment">// 作用是把值放到一个新的函子里面返回，返回的函子就是一个上下文</span></span><br><span class="line">    <span class="keyword">static</span> <span class="keyword">of</span> (value) &#123; </span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Container(value);</span><br><span class="line">    &#125;</span><br><span class="line">    ……  </span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 调用of的时候获得一个上下文，之后是在上下文中处理数据</span></span><br><span class="line">Contanier.of(<span class="number">2</span>)</span><br><span class="line">    .map(<span class="function"><span class="params">x</span> =&gt;</span> x + <span class="number">5</span>);</span><br></pre></td></tr></table></figure>

<blockquote>
<p>ES6 增加了 Array.of， 这使得数组成为了一个 Pointed 函子。</p>
</blockquote>
<p><code>**Array.of()**</code> 方法创建一个具有可变数量参数的新数组实例，而不考虑参数的数量或类型。</p>
<p> <code>**Array.of()**</code> 和 <code>**Array**</code> 构造函数之间的区别在于处理整数参数：<code>**Array.of(7)**</code> 创建一个具有单个元素 <strong>7</strong> 的数组，而 <strong><code>Array(7)</code></strong> 创建一个长度为7的空数组（<strong>注意：</strong>这是指一个有7个空位(empty)的数组，而不是由7个<code>undefined</code>组成的数组）。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.of(<span class="number">7</span>);       <span class="comment">// [7]</span></span><br><span class="line"><span class="built_in">Array</span>.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>); <span class="comment">// [1, 2, 3]</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">Array</span>(<span class="number">7</span>);          <span class="comment">// [ , , , , , , ]</span></span><br><span class="line"><span class="built_in">Array</span>(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>);    <span class="comment">// [1, 2, 3]</span></span><br></pre></td></tr></table></figure>

<p><strong>语法</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.of(element0[, element1[, ...[, elementN]]])</span><br></pre></td></tr></table></figure>

<p><strong>参数</strong></p>
<ul>
<li><p>element<em>N</em></p>
<p>任意个参数，将按顺序成为返回数组中的元素。</p>
</li>
</ul>
<p><strong>返回值</strong></p>
<p>新的 <a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array"><code>Array</code></a>。</p>
<p><strong>示例</strong></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.of(<span class="number">1</span>);         <span class="comment">// [1]</span></span><br><span class="line"><span class="built_in">Array</span>.of(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>);   <span class="comment">// [1, 2, 3]</span></span><br><span class="line"><span class="built_in">Array</span>.of(<span class="literal">undefined</span>); <span class="comment">// [undefined]</span></span><br></pre></td></tr></table></figure>

<h3 id="10-5-Monad-函子（单子）"><a href="#10-5-Monad-函子（单子）" class="headerlink" title="10.5 Monad 函子（单子）"></a>10.5 Monad 函子（单子）</h3><p>MayBe 函子很可能会出现嵌套，如果出现嵌套后，我们想要继续操作真正的value是有困难的。必须深入到 MayBe 内部进行操作。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> joinExample = MayBe.of(MayBe.of(<span class="number">5</span>));</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: MayBe &#123; value: 5 &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 这个时候我们想让5加上4，需要深入 MayBe 函子内部</span></span><br><span class="line">joinExample.map(<span class="function">(<span class="params">insideMayBe</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> insideMayBe.map(<span class="function">(<span class="params">value</span>) =&gt;</span> value + <span class="number">4</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: MayBe &#123; value: 9 &#125; &#125;</span></span><br></pre></td></tr></table></figure>

<p>我们这时就可以实现一个 join 方法来解决这个问题。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 如果通过 isNothing 的检查，就返回自身的 value</span></span><br><span class="line">MayBe.prototype.join = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : <span class="built_in">this</span>.value;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> joinExample2 = MayBe.of(MayBe.of(<span class="number">5</span>));</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: MayBe &#123; value: 5 &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 这个时候我们想让5加上4就很简单了。</span></span><br><span class="line">joinExample2.join().map(<span class="function">(<span class="params">value</span>) =&gt;</span> value + <span class="number">4</span>);</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: 9 &#125;</span></span><br></pre></td></tr></table></figure>

<p>再延伸一下，我们扩展一个 chain 方法。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">MayBe.prototype.chain = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> <span class="built_in">this</span>.map(fn).join();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>调用 chain 后就能把嵌套的 MayBe 展开了。</p>
<p>完整代码</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MayBe 跟上面的 Container 很相似</span></span><br><span class="line"><span class="keyword">const</span> MayBe = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line">MayBe.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MayBe(value);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 多了一个isNothing</span></span><br><span class="line">MayBe.prototype.isNoting = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.value === <span class="literal">null</span> || <span class="built_in">this</span>.value === <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 如果通过 isNothing 的检查，就返回自身的 value</span></span><br><span class="line">MayBe.prototype.join = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : <span class="built_in">this</span>.value;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 函子必定有 map,但是 map 的实现方式可能不同</span></span><br><span class="line">MayBe.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : MayBe.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 同时调用map和join方法</span></span><br><span class="line">MayBe.prototype.chain = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.map(fn).join();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试代码</span></span><br><span class="line"><span class="keyword">let</span> joinExample3 = MayBe.of(MayBe.of(<span class="number">5</span>));</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: MayBe &#123; value: 5 &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">joinExample3.chain(<span class="function">(<span class="params">insideMayBe</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> insideMayBe.map(<span class="function">(<span class="params">value</span>) =&gt;</span> value + <span class="number">4</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: 9 &#125;</span></span><br></pre></td></tr></table></figure>

<p>写成ES6格式</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// MayBe 跟上面的 Container 很相似</span></span><br><span class="line"><span class="keyword">const</span> MayBe = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">this</span>.value = value;</span><br><span class="line">&#125;</span><br><span class="line">MayBe.of = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">new</span> MayBe(value);</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 多了一个isNothing</span></span><br><span class="line">MayBe.prototype.isNoting = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.value === <span class="literal">null</span> || <span class="built_in">this</span>.value === <span class="literal">undefined</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 如果通过 isNothing 的检查，就返回自身的 value</span></span><br><span class="line">MayBe.prototype.join = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : <span class="built_in">this</span>.value;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 函子必定有 map,但是 map 的实现方式可能不同</span></span><br><span class="line">MayBe.prototype.map = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.isNoting() ? MayBe.of(<span class="literal">null</span>) : MayBe.of(fn(<span class="built_in">this</span>.value));</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 同时调用map和join方法</span></span><br><span class="line">MayBe.prototype.chain = <span class="function"><span class="keyword">function</span> (<span class="params">fn</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">this</span>.map(fn).join();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 测试代码</span></span><br><span class="line"><span class="keyword">let</span> joinExample3 = MayBe.of(MayBe.of(<span class="number">5</span>));</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: MayBe &#123; value: 5 &#125; &#125;</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">joinExample3.chain(<span class="function">(<span class="params">insideMayBe</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> insideMayBe.map(<span class="function">(<span class="params">value</span>) =&gt;</span> value + <span class="number">4</span>);</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// =&gt; MayBe &#123; value: 9 &#125;</span></span><br></pre></td></tr></table></figure>

<p><strong>Monad</strong> 其实就是一个含有 chain 方法的函子。只有of 和 map 的 MayBe 是一个函子，含有 chain 的函子是一个 Monad。</p>
<p><strong>什么时候使用Monad?</strong></p>
<ul>
<li>当一个函数返回一个函子的时候，我们就要想到monad，monad可以帮我们解决函子嵌套的问题。</li>
<li>当我们想要返回一个函数，这个函数返回一个值，这个时候可以调用<strong>map</strong> 方法</li>
<li>当我们想要去合并一个函数，但是这个函数返回一个函子，这个时候我们要用<strong>chain</strong> 方法</li>
</ul>
<h2 id="11-Pointfree与声明式编程"><a href="#11-Pointfree与声明式编程" class="headerlink" title="11.Pointfree与声明式编程"></a>11.Pointfree与声明式编程</h2><h3 id="前言-什么是Pointfree风格？"><a href="#前言-什么是Pointfree风格？" class="headerlink" title="前言 什么是Pointfree风格？"></a>前言 什么是Pointfree风格？</h3><p>什么是Pointfree风格？中译过来是<strong>无参数风格</strong>或者<strong>无值风格</strong>，意即为在编写程序时不关注具体数据以及对象，而只关注的是运算过程，具体的实现是函数的组合。</p>
<p><strong>Point Free：</strong> 我们可以把数据处理的过程定义成与数据无关的合成运算，不需要用到代表数据的那个参数，只要把简单的运算步骤合成到一起，在使用这种模式之前我们需要定义一些辅助的基本运算函数。</p>
<ul>
<li>不需要指明处理的数据</li>
<li>只需要合成运算过程</li>
<li>需要定义一些辅助的基本运算函数</li>
</ul>
<p>下文将用简单的例子带大家了解Pointfree风格~</p>
<h3 id="11-1-命令式编程的问题"><a href="#11-1-命令式编程的问题" class="headerlink" title="11.1 命令式编程的问题"></a>11.1 命令式编程的问题</h3><blockquote>
<p>“告诉计算机该怎么做，详细的执行步骤”</p>
</blockquote>
<p>考虑以下需求：小A去水果店去买水果，他想知道水果店里有存货并且最贵的水果名称是什么？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Apple&#x27;</span>, <span class="attr">price</span>: <span class="number">4</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Peach&#x27;</span>, <span class="attr">price</span>: <span class="number">14</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Grape&#x27;</span>, <span class="attr">price</span>: <span class="number">30</span>, <span class="attr">stock</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Pear&#x27;</span>, <span class="attr">price</span>: <span class="number">6</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">];</span><br></pre></td></tr></table></figure>

<p>我们常见的实现方式一般如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Ex 1</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Apple&#x27;</span>, <span class="attr">price</span>: <span class="number">4</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Peach&#x27;</span>, <span class="attr">price</span>: <span class="number">14</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Grape&#x27;</span>, <span class="attr">price</span>: <span class="number">30</span>, <span class="attr">stock</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Pear&#x27;</span>, <span class="attr">price</span>: <span class="number">6</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fruitsHaveStock = fruits.filter(<span class="function"><span class="params">fruit</span> =&gt;</span> fruit.stock);</span><br><span class="line"><span class="keyword">const</span> sortedDescFruits = fruitsHaveStock.sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b.price - a.price);</span><br><span class="line"><span class="keyword">const</span> mostExpensiveFruitName = sortedDescFruits[<span class="number">0</span>].name;</span><br><span class="line"><span class="built_in">console</span>.log(mostExpensiveFruitName); <span class="comment">// Peach</span></span><br></pre></td></tr></table></figure>

<p>这个是很明显的命令式编程，因为大脑会习惯线性的去理解事物，所以我们自然而然的罗列了这个需求的实现步骤，从而实现了上述的需求。但是这样的代码缺点如下：</p>
<ol>
<li>代码难以复用。</li>
<li>代码自上而下，并没有组织，从阅读上需要完整的从上至下阅读，才能了解发生了什么事。</li>
<li>可以观察到<code>fruits.filter(fruit =&gt; fruit.stock);</code>中的<code>fruit</code>参数、<code>fruitsHaveStock</code>、<code>sortedDescFruits</code>这些都是Point，换句话说，我们的程序关注了被操作的数据！</li>
</ol>
<h3 id="11-2-运用声明式编程和无值风格优化代码"><a href="#11-2-运用声明式编程和无值风格优化代码" class="headerlink" title="11.2 运用声明式编程和无值风格优化代码"></a>11.2 运用声明式编程和无值风格优化代码</h3><blockquote>
<p>“告诉计算机做什么，我们想要什么”</p>
</blockquote>
<h4 id="11-2-1-声明式编程风格"><a href="#11-2-1-声明式编程风格" class="headerlink" title="11.2.1 声明式编程风格"></a>11.2.1 声明式编程风格</h4><p>上述代码用声明式的风格重写一下~</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Ex 2</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> fruits = [</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Apple&#x27;</span>, <span class="attr">price</span>: <span class="number">4</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Peach&#x27;</span>, <span class="attr">price</span>: <span class="number">14</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Grape&#x27;</span>, <span class="attr">price</span>: <span class="number">30</span>, <span class="attr">stock</span>: <span class="literal">false</span> &#125;,</span><br><span class="line">    &#123; <span class="attr">name</span>: <span class="string">&#x27;Pear&#x27;</span>, <span class="attr">price</span>: <span class="number">6</span>, <span class="attr">stock</span>: <span class="literal">true</span> &#125;,</span><br><span class="line">];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> filter = <span class="function"><span class="params">predicate</span> =&gt;</span> <span class="function"><span class="params">list</span> =&gt;</span> list.filter(predicate);</span><br><span class="line"><span class="keyword">const</span> propEq = <span class="function">(<span class="params">key, value</span>) =&gt;</span> <span class="function"><span class="params">target</span> =&gt;</span> target[key] === value;</span><br><span class="line"><span class="keyword">const</span> compose = <span class="function">(<span class="params">...funcs</span>) =&gt;</span> <span class="function"><span class="params">result</span> =&gt;</span> [...funcs]</span><br><span class="line">    .reverse()</span><br><span class="line">    .reduce(<span class="function">(<span class="params">result, fn</span>) =&gt;</span> fn(result), result);</span><br><span class="line"><span class="keyword">const</span> sort = <span class="function"><span class="params">func</span> =&gt;</span> <span class="function"><span class="params">list</span> =&gt;</span> list.sort(func);</span><br><span class="line"><span class="keyword">const</span> prop = <span class="function"><span class="params">key</span> =&gt;</span> <span class="function"><span class="params">target</span> =&gt;</span> target[key];</span><br><span class="line"><span class="keyword">const</span> head = <span class="function"><span class="params">list</span> =&gt;</span> list.slice(<span class="number">0</span>, <span class="number">1</span>).pop();</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getHaveStock</span>(<span class="params">list</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> filter(propEq(<span class="string">&#x27;stock&#x27;</span>, <span class="literal">true</span>))(list);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sortByPriceDesc</span>(<span class="params">list</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b.price - a.price)(list);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getName</span>(<span class="params">target</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> prop(<span class="string">&#x27;name&#x27;</span>)(target);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMostExpensiveFruitName</span>(<span class="params">list</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> compose(</span><br><span class="line">    	getName, head, sortByPriceDesc, getHaveStock</span><br><span class="line">    )(list);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getMostExpensiveFruitName(fruits)); <span class="comment">// Peach</span></span><br></pre></td></tr></table></figure>

<p>同学们对比Ex 1和Ex 2代码，可以发现两点：</p>
<ol>
<li>我写了一些通用工具方法<code>filter</code>、<code>propEq</code>、<code>compose</code>等等</li>
<li>最后compose的时候，可以明确知道数据流从 <strong>getHaveStock -&gt; sortByPriceDesc -&gt; head -&gt; getName</strong>。而我们不需要了解这些函数的细节实现，从这些函数名称上来看，可以清晰的知道我们要对接收的数据进行的操作！</li>
</ol>
<h4 id="11-2-2-Pointfree风格，不关注数据！"><a href="#11-2-2-Pointfree风格，不关注数据！" class="headerlink" title="11.2.2 Pointfree风格，不关注数据！"></a>11.2.2 Pointfree风格，不关注数据！</h4><p>但是问题来了，细心的同学应该发现了一个问题，虽然说我们改成了声明式编程的风格，但是我们还是关注了要处理的数据本身（也就是值），什么意思？</p>
<p>比如这个函数：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getHaveStock</span>(<span class="params">list</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> filter(propEq(<span class="string">&#x27;stock&#x27;</span>, <span class="literal">true</span>))(list);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>因为我们只想关心怎么运算操作！list参数对于函数本身实现来说，完全属于多余，且也不需要关注的。</p>
<p>于是我们可以改写如下：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> getHaveStock = filter(propEq(<span class="string">&#x27;stock&#x27;</span>, <span class="literal">true</span>));</span><br></pre></td></tr></table></figure>

<p>其余<code>sortByPriceDesc</code>, <code>getName</code>, <code>getMostExpensiveFruitName</code>同理优化。于是就达到了我们说的 <strong>Pointfree</strong> 啦！（因为我们干掉了point -&gt; list参数）</p>
<p>当然，说不定有些同学发发牢骚了：“代码好像变得更长了…而且还写了一大堆莫名其妙的工具方法，我才不想这么干呢！”</p>
<p>这位同学说的有道理！请继续往下看~</p>
<h3 id="11-3-Ramda"><a href="#11-3-Ramda" class="headerlink" title="11.3 Ramda"></a>11.3 Ramda</h3><blockquote>
<p>一款实用的，专门为函数式编程风格而设计的JavaScript函数式编程库</p>
</blockquote>
<p>如果决心了解JavaScript函数式编程，并且想要用Pointfree风格优化一下代码，那么ramda是值得学习的！它帮我们省掉了上述Ex 2写的大量工具函数。 官网贴上：<a target="_blank" rel="noopener" href="https://ramdajs.com/">ramda</a></p>
<p>所以，我们使用<strong>ramda</strong>改写一下~</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Ex 3</span></span><br><span class="line"><span class="keyword">const</span> &#123; filter, propEq, sort, prop, compose, head &#125; = <span class="built_in">require</span>(<span class="string">&#x27;ramda&#x27;</span>);</span><br><span class="line"><span class="keyword">const</span> haveStock = propEq(<span class="string">&#x27;stock&#x27;</span>, <span class="literal">true</span>);</span><br><span class="line"><span class="keyword">const</span> getHaveStock = filter(haveStock);</span><br><span class="line"><span class="keyword">const</span> sortByPriceDesc = sort(<span class="function">(<span class="params">a, b</span>) =&gt;</span> b.price - a.price);</span><br><span class="line"><span class="keyword">const</span> getName = prop(<span class="string">&#x27;name&#x27;</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getMostExpensiveFruitName = compose(</span><br><span class="line">  getName, head, sortByPriceDesc, getHaveStock</span><br><span class="line">);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getMostExpensiveFruitName(fruits)); <span class="comment">// Peach</span></span><br></pre></td></tr></table></figure>

<p>上述代码的优点体现在以下三方面：</p>
<ol>
<li>代码从可读性上来说提升了</li>
<li>代码可复用性增强了，haveStock、getHaveStock、sortByPriceDesc、getName这些函数并没有关注被处理的数据，而是关注处理本身。</li>
<li>纯函数利于写单元测试</li>
</ol>
<p>备注：ramda其实可以大致理解为函数式风格的lodash工具库，它和lodash的区别主要在于两点：</p>
<ol>
<li>Ramda函数本身都是自动柯里化的。</li>
<li>Ramda函数参数的排列顺序更便于柯里化。要操作的数据通常在最后面。（也意味着通常第一个传入的参数是函数方法）。</li>
</ol>
<h3 id="小结"><a href="#小结" class="headerlink" title="小结"></a>小结</h3><p>Pointfree风格的确需要一定的时间才能习惯，但是也不能一概而论把所有函数的参数都移除掉，具体情况还是需要具体分析。Pointfree风格虽然有时候也会造成一些困惑，但的确让代码更加简洁和易于理解了。</p>
<p>当然，如果愿意花点时间去练习和习惯Pointfree风格，相信还是会很值得的。</p>
<h2 id="12-递归"><a href="#12-递归" class="headerlink" title="12.递归"></a>12.递归</h2><h3 id="前言：什么是递归"><a href="#前言：什么是递归" class="headerlink" title="前言：什么是递归"></a>前言：什么是递归</h3><blockquote>
<p>递归和迭代是一枚硬币的两面，在不可变的条件下，递归提供了一种更具表现力、强大且优秀的迭代替代方法</p>
</blockquote>
<p>递归函数由以下两个主要部分组成：</p>
<ul>
<li>基准</li>
<li>递归条件</li>
</ul>
<p>递归主要的核心思想是将问题分解为较小的问题，逐个解决后再组合，构建出整个问题的答案。</p>
<p>具体概念不详述，可谷歌百度自行搜索。递归适合解决类似XML解析、语法树构建，深度遍历等问题。</p>
<p>而在Haskell这种纯函数编程语言里，原本是没有循环结构的，递归是天然代替循环的，比如求和函数（当然，Haskell有原生的sum方法支持）实现，如下所示：</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">sum&#x27;</span> :: <span class="type">Num</span> a =&gt; [a] -&gt; a</span><br><span class="line"><span class="title">sum&#x27;</span> []  = <span class="number">0</span></span><br><span class="line"><span class="title">sum&#x27;</span> (x:xs) = x + sum&#x27; xs</span><br></pre></td></tr></table></figure>

<p>再看阶乘函数的Haskell实现，如下所示：</p>
<figure class="highlight haskell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title">factorial</span> :: (<span class="type">Integral</span> a) =&gt; a -&gt; a  </span><br><span class="line"><span class="title">factorial</span> <span class="number">0</span> = <span class="number">1</span>  </span><br><span class="line"><span class="title">factorial</span> n = n * factorial (n - <span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>你会发现函数的声明基本表达了上述所说的递归两个主要部分。不得不承认，很优雅！</p>
<p>递归适当时候可以优雅的解决迭代不适合处理的问题。掌握递归思考的方式是一个长期训练的过程。</p>
<p>下文将带大家学习几个递归的姿势，由于篇幅有限，不详述原理。</p>
<p>（同学们莫慌，下文将用JavaScript举例，毕竟它才是我目前的恰饭工具哈哈）</p>
<h3 id="12-1-求和的几种姿势"><a href="#12-1-求和的几种姿势" class="headerlink" title="12.1 求和的几种姿势"></a>12.1 求和的几种姿势</h3><p>考虑给一个数组求和：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br></pre></td></tr></table></figure>

<h4 id="12-1-1-命令式"><a href="#12-1-1-命令式" class="headerlink" title="12.1.1 命令式"></a>12.1.1 命令式</h4><p>命令式的开发思维，会很自然写出以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="keyword">let</span> total = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">for</span>(<span class="keyword">let</span> i = <span class="number">0</span>; i &lt; nums.length; i++) &#123;</span><br><span class="line">	total += nums[i];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(total); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<h4 id="12-1-2-声明式"><a href="#12-1-2-声明式" class="headerlink" title="12.1.2 声明式"></a>12.1.2 声明式</h4><p>更进一步，学了点函数式编程，会写出以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="keyword">const</span> add = <span class="function">(<span class="params">x, y</span>) =&gt;</span> x + y;</span><br><span class="line"><span class="keyword">const</span> sum = <span class="function">(<span class="params">...nums</span>) =&gt;</span> nums.reduce(add, <span class="number">0</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(sum(...nums)); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<h3 id="12-2-递归"><a href="#12-2-递归" class="headerlink" title="12.2 递归"></a>12.2 递归</h3><p>了解递归的同学，写出来以下代码：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getTotal</span>(<span class="params">sum, num, ...nums</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (nums.length === <span class="number">0</span>) &#123;</span><br><span class="line">    	<span class="keyword">return</span> sum + num;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> sum + getTotal(num, ...nums);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getTotal(...nums)); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<p>但是，目之所及，递归还是很少用的，不仅仅常见的缺乏递归思维问题，也是有性能问题的考虑，大家会发现写递归存在栈溢出的问题:</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102848.webp" alt="img"></p>
<p>于是我写了个函数，测试一下Chrome浏览器支持递归的深度是多少？</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getTotal</span>(<span class="params">sum, num, ...nums</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (nums.length === <span class="number">0</span>) &#123;</span><br><span class="line">    	<span class="keyword">return</span> sum + num;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> sum + getTotal(num, ...nums);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getMaximumCallStack</span>(<span class="params">getTotal</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">const</span> f = <span class="function"><span class="params">n</span> =&gt;</span> getTotal(...<span class="string">&#x27;1&#x27;</span>.repeat(n).split(<span class="string">&#x27;&#x27;</span>).map(<span class="built_in">Number</span>));</span><br><span class="line">    <span class="keyword">let</span> i = <span class="number">1</span>;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">while</span>(<span class="literal">true</span>) &#123;</span><br><span class="line">        <span class="keyword">try</span> &#123;</span><br><span class="line">            <span class="keyword">const</span> res = f(i);</span><br><span class="line">            <span class="built_in">console</span>.log(<span class="string">`Stack size: <span class="subst">$&#123;i&#125;</span>, f(<span class="subst">$&#123;i&#125;</span>)=<span class="subst">$&#123;res&#125;</span>`</span>);</span><br><span class="line">            i++;</span><br><span class="line">        &#125; <span class="keyword">catch</span>(e) &#123;</span><br><span class="line">            <span class="built_in">console</span>.info(<span class="string">`Maximum call stack size: <span class="subst">$&#123;i&#125;</span>`</span>);</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">getMaximumCallStack(getTotal);</span><br></pre></td></tr></table></figure>

<p>测试了上述写的getTotal递归，</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102902.webp" alt="img"></p>
<p>Chrome宝宝竟然只是到了484层栈就跪了，实在不敢相信！</p>
<p>————浏览器三八分割线————</p>
<p>Safari宝宝表现如何呢？</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102939.webp" alt="img"></p>
<p>貌似比Chrome好一丢丢，不过也没什么很大的区别…</p>
<p>那这样让我们如何愉快地使用递归呀？</p>
<h3 id="12-3-递归的几种优化方式"><a href="#12-3-递归的几种优化方式" class="headerlink" title="12.3 递归的几种优化方式"></a>12.3 递归的几种优化方式</h3><p>如上文所述，递归虽然优雅，但是常常会遇到栈溢出的情况，那么这种问题怎么优化呢？以下三种优化方式：</p>
<h4 id="12-3-1-PTC（Proper-Tail-Calls-适当的尾调用）"><a href="#12-3-1-PTC（Proper-Tail-Calls-适当的尾调用）" class="headerlink" title="12.3.1 PTC（Proper Tail Calls 适当的尾调用）"></a>12.3.1 PTC（Proper Tail Calls 适当的尾调用）</h4><p>ES6的尾调用优化只在严格模式下开启，正常模式是无效的。</p>
<p>适当的尾调用可以避免递归调用时的栈膨胀。不过，为了做到适当的尾调用，我们<strong>首先得有一个尾调用</strong>。</p>
<p>那什么是尾调用？</p>
<p>尾调用是执行时不会造成栈膨胀的函数。尾调用是执行<code>return</code>之前要做的最后一个操作，而这个被调用函数的返回值由调用它的函数返回。调用函数不能是<a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*">生成器函数。</a></p>
<p>例如</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">f</span>(<span class="params">x</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> g(x);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如果你研究编译器理论，那么可以看看<a target="_blank" rel="noopener" href="http://www.ecma-international.org/ecma-262/6.0/index.html#sec-isintailposition">ECMA规范中的正式定义。</a></p>
<p>PTC一定要运行在严格模式下，文件开始声明<code>&quot;use strict&quot;;</code></p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getTotal_PTC</span>(<span class="params">sum, num, ...nums</span>) </span>&#123;</span><br><span class="line">    sum += num;</span><br><span class="line">    <span class="keyword">if</span> (nums.length === <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> sum;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> getTotal_PTC(sum, ...nums);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getTotal_PTC(...nums)); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<p>PTC版的递归其实和上文写的递归只有些微写法上的区别：</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 正常递归</span></span><br><span class="line"><span class="keyword">return</span> sum + getTotal(num, ...nums);</span><br><span class="line"><span class="comment">// PTC版的递归</span></span><br><span class="line"><span class="keyword">return</span> getTotal_PTC(sum, ...nums);</span><br></pre></td></tr></table></figure>

<p>这次我们给函数传递了两个参数：一个是我们想要计算剩下的数的和（<code>...nums</code>），一个是累积的和，即<code>sum</code>。</p>
<p>改成PTC写法之后，支持支持PTC优化的浏览器，可以不断重复利用原有的栈，从而避免了栈溢出的问题。（原理大致上是由于浏览器不用保留记住每一次递归中的值，在这个函数里特指 <strong>sum</strong> + getTotal(num, …nums) 中的sum变量值，从而新栈替换旧栈。</p>
<p>支持PTC优化的浏览器不多，目前可能只有Safari支持，仍然为了眼见为实，在Chrome和Safari两个浏览器进行了测试。</p>
<p>运行上述工具方法测试：<code>getMaximumCallStack(getTotal_PTC)</code></p>
<p>Chrome宝宝很可惜的偷懒了，木有支持~（残念），见下图：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102934.webp" alt="img"></p>
<p>Safari宝宝果然优秀，对其有所支持！跑了一段时间，未见溢出，见下图：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421102959.webp" alt="img"></p>
<p>要记住，<strong>适当的尾调用不一定会让代码跑得更快</strong>。实际上，<a target="_blank" rel="noopener" href="https://github.com/tc39/proposal-ptc-syntax#performance">多数情况下，有了它反而会更慢。</a></p>
<p>然而，使用适当的尾调用除了可以节省调用栈的内存占用，还会由于在局部声明的对象使运行递归函数占用的内存更少。由于下一次递归调用不必使用当前帧中的任何变量，因此垃圾收集器就可以把当前帧中的所有对象销毁了。但在“非尾递归”函数中，每调用一次递归函数，都要分配一次内存。毕竟所有帧在最后一次递归调用（即返回“既定情况”的调用）返回前，都必须保存在帧里。</p>
<p>尾调用的优化请参考<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903522610348045">JavaScript中的递归、PTC、TCO和STC</a></p>
<h4 id="12-3-2-CPS（Continuation-Passing-Style）"><a href="#12-3-2-CPS（Continuation-Passing-Style）" class="headerlink" title="12.3.2 CPS（Continuation Passing Style）"></a>12.3.2 CPS（Continuation Passing Style）</h4><p>在其他语言中，有一个叫做 <a target="_blank" rel="noopener" href="https://en.wikipedia.org/wiki/Thread-local_storage">Thread-local storage</a> 的东西，然而在 Javascript 中，并不存在多线程这种概念（相对而言，Web Worker 等与主进程并不冲突），于是 CLS ，Continuation-local Storage，一个类似于 TLS，得名于函数式编程中的 Continuation-passing style，旨在链式函数调用过程中维护一个持久的数据。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getTotal_CPS = (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">...nums</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> recur(nums, <span class="function"><span class="params">v</span> =&gt;</span> v);</span><br><span class="line">	&#125;;</span><br><span class="line"></span><br><span class="line">	<span class="function"><span class="keyword">function</span> <span class="title">recur</span>(<span class="params">[sum, ...nums], identity</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (nums.length === <span class="number">0</span>) &#123;</span><br><span class="line">        	<span class="keyword">return</span> identity(sum);</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        	<span class="keyword">return</span> recur(nums, <span class="function"><span class="params">v</span> =&gt;</span> identity(sum + v));</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)();</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getTotal_CPS(...nums)); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<p>这种优化技巧通过创建额外的闭包函数：</p>
<ol>
<li>将值的计算延迟</li>
<li>避免调用栈的堆积</li>
</ol>
<p>但是不可避免的消耗了更多的内存用来存放这些多余的闭包函数。 （关于具体原理比较复杂，有空单独写篇文章论述）</p>
<p>Chrome浏览器测试如下图：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421103013.webp" alt="img"></p>
<p>仍然栈溢出，但是栈的深度多了很多~</p>
<p>更多CPS相关调用可以阅读：<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904201101770766">什么是 CLS？在浏览器和 Node.js 中实现 CLS</a>和<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904051872628749">Javascript与CLS（Continuation-local Storage）</a></p>
<h4 id="12-3-3-Trampoline（蹦床函数）"><a href="#12-3-3-Trampoline（蹦床函数）" class="headerlink" title="12.3.3 Trampoline（蹦床函数）"></a>12.3.3 Trampoline（蹦床函数）</h4><p>Trampoline（蹦床函数）的基本原理是，使用蹦床展平调用，而不是深度嵌套的递归调用。</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> nums = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">5</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getTotal_f</span>(<span class="params">sum, num, ...nums</span>) </span>&#123;</span><br><span class="line">    sum += num;</span><br><span class="line">    <span class="keyword">if</span> (nums.length === <span class="number">0</span>) &#123;</span><br><span class="line">    	<span class="keyword">return</span> sum;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    	<span class="keyword">return</span> <span class="function">() =&gt;</span> getTotal_f(sum, ...nums);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trampoline</span>(<span class="params">f</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">trampolined</span>(<span class="params">...args</span>) </span>&#123;</span><br><span class="line">        <span class="keyword">let</span> result = f(...args);</span><br><span class="line">        <span class="comment">// 这段是将递归转换为迭代的精髓</span></span><br><span class="line">        <span class="keyword">while</span> (<span class="keyword">typeof</span> result == <span class="string">&quot;function&quot;</span>) &#123;</span><br><span class="line">        	result = result();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> result;</span><br><span class="line">    &#125;;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> getTotal_trampoline = trampoline(getTotal_f);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(getTotal_trampoline(...nums)); <span class="comment">// 15</span></span><br></pre></td></tr></table></figure>

<p>这种思维技巧将递归巧妙的转换为了迭代！ 写法保持了递归的思维，但是经过trampoline工具函数的处理，实际上交给浏览器执行的时候变成了迭代。</p>
<p>Chrome测试如下：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210421103028.webp" alt="img"></p>
<p>速度飞快！丝滑流畅~</p>
<p>考虑到内存堆栈问题，trampoline还是蛮适合作为折中的方案的。</p>
<p>更多采用Trampoline的了解可以参考<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844904035171074055">前端递归思想（禁止套娃）</a>和<a target="_blank" rel="noopener" href="https://juejin.cn/post/6844903569032740872">蹦床（trampoline）原理</a></p>
<h3 id="小结-1"><a href="#小结-1" class="headerlink" title="小结"></a>小结</h3><p>谨记：递归的目标是写出更具有可读性的代码。所以运用递归时考虑以下两点：</p>
<ul>
<li>编写迭代循环之前，反思是不是可以用递归更好的表述！</li>
<li>编写递归之前，反思是不是没有必要使用递归？</li>
</ul>
<h2 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h2><p>使用函数式编程最大的好处在于其能提高我们代码的可读性。</p>
<p>编程中有下面这种说法：</p>
<blockquote>
<p>你不理解的代码，实际上就是不值得信任的代码。你不信任的代码，实际上就是你不理解的代码。</p>
</blockquote>
<p>所谓的理解实际上是指不执行，仅仅读一下，你就能知道某段代码到底要做什么。</p>
<p>已 <code>map</code> 和 <code>for</code> 为例来说： 看到 <code>map</code> 就算我们不去细读其中的代码，也能想到这里想做的是对原始的值进行一定的转换并返回一个新的值； 看到 <code>for</code>，不去进一步的阅读其中的代码，你并不能很快的知晓这段代码要做什么。</p>
<p>当然可读性与对熟练程度也强相关。印象还很深，最初接触 <code>map</code> 时，我并没有马上感觉到它很好，我还是会觉得别扭，但是后来很多情况下就会首选使用 <code>map</code> 。</p>
<p>类似诗词中的语码那样，我们需要熟悉函数式编程中的一些概念，才能更好的理解函数式语句。这种熟悉需要一定的成本，所以在很多人看来，函数式编程和可读性存在下面这张图这样的关系：</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210605153710.png" alt="img">函数式编程与可读性的关系</p>
<p>一些函数式编程中的概念学习成本不高，而且能极大的提高代码的可读性，比如 <code>map</code>,<code>filter</code> ，所以大部分人在刚刚开始接触函数式编程会觉得其还挺好的，但是比如对<code>reduce</code>,<code>compose</code>,<code>transduce</code>，刚开始接触就会觉得不熟悉，不好理解，也就觉得可读性低。不过觉得不好理解还是不熟悉造成的，多看多联系，你会发现无论是书写还是阅读都变得更为自然起来。</p>
<p>这里我们简单介绍一下 <code>imperative</code> 和 <code>declarative</code></p>
<ul>
<li>指令式编程（imperative）关注告诉计算机如何一步步的做某件事情，这也是大多数人习惯的代码风格；</li>
<li>声明式编程（declarative）则关注每一步的输出，函数式编程则从本质上更具声明式特点。</li>
<li>声明式编程比指令式编程要容易理解。计算机擅长指令式，而我们擅长声明式。</li>
</ul>
<p>如果我们合理的使用了函数式编程，我们的代码主体可能就会变成一个个「独立且拥有合适名称的纯函数」，若干「纯函数的组合」，「集中处理的副作用」。想要了解整体代码逻辑，只需去阅读函数组合在语意上做了什么事情，副作用做了什么，想要了解具体某个纯函数做了什么时，可以单独去查看其定义，而不用去关心其它的函数。</p>
<p>学习函数式编程并不是让自己看起来有多么聪明，也不是为了迷惑队友（哈哈），也不是单纯为了学习而学习。它的实际意义在于，给函数调用穿上语义化的衣服，让实际的应用代码最终更可读友好，利于维护~ 当然与此同时，也会训练自己写出声明式的代码，虽然道阻且长，但总有一天我要学会它们。</p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/javascript/" rel="tag"><i class="fa fa-tag"></i> javascript</a>
              <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B/" rel="tag"><i class="fa fa-tag"></i> 函数式编程</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/04/21/%E5%88%A9%E7%94%A8Typora+PicGo+Github+Jsdelivr%E6%90%AD%E5%BB%BA%E5%B1%9E%E4%BA%8E%E8%87%AA%E5%B7%B1%E7%9A%84%E5%9B%BE%E5%BA%8A/" rel="prev" title="利用Typora+PicGo+Github+Jsdelivr搭建属于自己的图床">
      <i class="fa fa-chevron-left"></i> 利用Typora+PicGo+Github+Jsdelivr搭建属于自己的图床
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/05/03/%E7%BB%BC%E5%90%88%E9%9D%A2%E8%AF%95%E9%97%AE%E9%A2%98/" rel="next" title="综合面试问题">
      综合面试问题 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E4%BB%80%E4%B9%88%E6%98%AF%E5%87%BD%E6%95%B0%E5%BC%8F%E7%BC%96%E7%A8%8B"><span class="nav-text">1.什么是函数式编程</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E9%97%AD%E5%8C%85"><span class="nav-text">2.闭包</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-unary"><span class="nav-text">3.unary</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95"><span class="nav-text">ES6简化写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95"><span class="nav-text">ES6常规写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-identity"><span class="nav-text">4.identity</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95-1"><span class="nav-text">ES6简化写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95-1"><span class="nav-text">ES6常规写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#5-constant"><span class="nav-text">5.constant</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95-2"><span class="nav-text">ES6简化写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95-2"><span class="nav-text">ES6常规写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#6-spreadArgs-amp-gatherArgs"><span class="nav-text">6.spreadArgs &amp; gatherArgs</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95-3"><span class="nav-text">ES6简化写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95-3"><span class="nav-text">ES6常规写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#7-partial-amp-curry%EF%BC%88%E5%81%8F%E5%87%BD%E6%95%B0%E4%B8%8E%E6%9F%AF%E9%87%8C%E5%8C%96%EF%BC%89"><span class="nav-text">7.partial &amp; curry（偏函数与柯里化）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%81%8F%E5%87%BD%E6%95%B0ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95"><span class="nav-text">偏函数ES6简化写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%81%8F%E5%87%BD%E6%95%B0ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95"><span class="nav-text">偏函数ES6常规写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96ES6%E5%B8%B8%E8%A7%84%E5%86%99%E6%B3%95"><span class="nav-text">函数柯里化ES6常规写法</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%87%BD%E6%95%B0%E6%9F%AF%E9%87%8C%E5%8C%96ES6%E7%AE%80%E5%8C%96%E5%86%99%E6%B3%95"><span class="nav-text">函数柯里化ES6简化写法</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#8-compose%EF%BC%88%E5%87%BD%E6%95%B0%E5%90%88%E6%88%90%EF%BC%89"><span class="nav-text">8.compose（函数合成）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E%E6%A0%88%E7%9A%84compose%E5%87%BD%E6%95%B0"><span class="nav-text">基于栈的compose函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%87%BD%E6%95%B0reduce%E7%9A%84compose%E5%87%BD%E6%95%B0"><span class="nav-text">使用函数reduce的compose函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E9%80%92%E5%BD%92%E6%9D%A5%E5%AE%9E%E7%8E%B0compose"><span class="nav-text">使用递归来实现compose</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#redux-amp-koa-compose"><span class="nav-text">redux &amp; koa-compose</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#9-pipe%EF%BC%88%E7%AE%A1%E9%81%93-%E5%BA%8F%E5%88%97%EF%BC%89"><span class="nav-text">9.pipe（管道&#x2F;序列）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%9F%BA%E4%BA%8E%E9%98%9F%E5%88%97%E7%9A%84pipe%E5%87%BD%E6%95%B0"><span class="nav-text">基于队列的pipe函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E5%87%BD%E6%95%B0reduce%E7%9A%84pipe%E5%87%BD%E6%95%B0"><span class="nav-text">使用函数reduce的pipe函数</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E9%80%92%E5%BD%92%E6%9D%A5%E5%AE%9E%E7%8E%B0pipe"><span class="nav-text">使用递归来实现pipe</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#10-Functor%EF%BC%88%E5%87%BD%E5%AD%90%EF%BC%89"><span class="nav-text">10.Functor（函子）</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%89%8D%E8%A8%80-%E4%BB%80%E4%B9%88%E6%98%AF%E5%87%BD%E5%AD%90%EF%BC%9F"><span class="nav-text">前言 什么是函子？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-1-%E5%AE%9E%E7%8E%B0%E4%B8%80%E4%B8%AA%E5%87%BD%E5%AD%90"><span class="nav-text">10.1 实现一个函子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-2-MayBe-%E5%87%BD%E5%AD%90"><span class="nav-text">10.2 MayBe 函子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-3-Either-%E5%87%BD%E5%AD%90"><span class="nav-text">10.3 Either 函子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-4-Pointed-%E5%87%BD%E5%AD%90"><span class="nav-text">10.4 Pointed 函子</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#10-5-Monad-%E5%87%BD%E5%AD%90%EF%BC%88%E5%8D%95%E5%AD%90%EF%BC%89"><span class="nav-text">10.5 Monad 函子（单子）</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#11-Pointfree%E4%B8%8E%E5%A3%B0%E6%98%8E%E5%BC%8F%E7%BC%96%E7%A8%8B"><span class="nav-text">11.Pointfree与声明式编程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%89%8D%E8%A8%80-%E4%BB%80%E4%B9%88%E6%98%AFPointfree%E9%A3%8E%E6%A0%BC%EF%BC%9F"><span class="nav-text">前言 什么是Pointfree风格？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#11-1-%E5%91%BD%E4%BB%A4%E5%BC%8F%E7%BC%96%E7%A8%8B%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-text">11.1 命令式编程的问题</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#11-2-%E8%BF%90%E7%94%A8%E5%A3%B0%E6%98%8E%E5%BC%8F%E7%BC%96%E7%A8%8B%E5%92%8C%E6%97%A0%E5%80%BC%E9%A3%8E%E6%A0%BC%E4%BC%98%E5%8C%96%E4%BB%A3%E7%A0%81"><span class="nav-text">11.2 运用声明式编程和无值风格优化代码</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#11-2-1-%E5%A3%B0%E6%98%8E%E5%BC%8F%E7%BC%96%E7%A8%8B%E9%A3%8E%E6%A0%BC"><span class="nav-text">11.2.1 声明式编程风格</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#11-2-2-Pointfree%E9%A3%8E%E6%A0%BC%EF%BC%8C%E4%B8%8D%E5%85%B3%E6%B3%A8%E6%95%B0%E6%8D%AE%EF%BC%81"><span class="nav-text">11.2.2 Pointfree风格，不关注数据！</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#11-3-Ramda"><span class="nav-text">11.3 Ramda</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93"><span class="nav-text">小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#12-%E9%80%92%E5%BD%92"><span class="nav-text">12.递归</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%89%8D%E8%A8%80%EF%BC%9A%E4%BB%80%E4%B9%88%E6%98%AF%E9%80%92%E5%BD%92"><span class="nav-text">前言：什么是递归</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#12-1-%E6%B1%82%E5%92%8C%E7%9A%84%E5%87%A0%E7%A7%8D%E5%A7%BF%E5%8A%BF"><span class="nav-text">12.1 求和的几种姿势</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#12-1-1-%E5%91%BD%E4%BB%A4%E5%BC%8F"><span class="nav-text">12.1.1 命令式</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#12-1-2-%E5%A3%B0%E6%98%8E%E5%BC%8F"><span class="nav-text">12.1.2 声明式</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#12-2-%E9%80%92%E5%BD%92"><span class="nav-text">12.2 递归</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#12-3-%E9%80%92%E5%BD%92%E7%9A%84%E5%87%A0%E7%A7%8D%E4%BC%98%E5%8C%96%E6%96%B9%E5%BC%8F"><span class="nav-text">12.3 递归的几种优化方式</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#12-3-1-PTC%EF%BC%88Proper-Tail-Calls-%E9%80%82%E5%BD%93%E7%9A%84%E5%B0%BE%E8%B0%83%E7%94%A8%EF%BC%89"><span class="nav-text">12.3.1 PTC（Proper Tail Calls 适当的尾调用）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#12-3-2-CPS%EF%BC%88Continuation-Passing-Style%EF%BC%89"><span class="nav-text">12.3.2 CPS（Continuation Passing Style）</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#12-3-3-Trampoline%EF%BC%88%E8%B9%A6%E5%BA%8A%E5%87%BD%E6%95%B0%EF%BC%89"><span class="nav-text">12.3.3 Trampoline（蹦床函数）</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%B0%8F%E7%BB%93-1"><span class="nav-text">小结</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
